/*
 * @Descripttion:
 * @version:
 * @Author: ChenXiang
 * @Date: 2021-05-10 09:04:02
 * @LastEditors: ChenXiang
 * @LastEditTime: 2021-08-19 13:53:44
 */
import React from "react";
export type Props = {
  count: number;
  autoplay: boolean; // 是否自动开始倒计时。可以由外界控制 timestamp 更新再传入
  endCallback: any;
  type: string;
};
type State = {
  count: number;
  resultHour: string;
  resultMinute: string;
  resultSecond: string;
  autoplay: boolean;
};

export default class Timer extends React.Component<Props, State> {
  interval: any;
  static defaultProps: { autoplay: boolean; count: number };
  constructor(props: Props | Readonly<Props>) {
    super(props);
    this.state = {
      count: props.count,
      resultHour: "00",
      resultMinute: "00",
      resultSecond: "00",
      autoplay: props.autoplay
    };
    this.interval = null;
  }

  componentWillReceiveProps(props) {
    if (props.count !== this.props.count) {
      this.setState({
        count: props.count
      });
    }

    if (props.autoplay !== this.props.autoplay) {
      this.setState(
        {
          autoplay: props.autoplay
        },
        () => {
          this.start();
        }
      );
    }
  }

  componentDidMount() {
    this.start();
  }

  start = () => {
    if (this.state.autoplay === false) {
      return;
    }
    this.interval = setInterval(() => {
      const data: any = this.state.count;
      const currentCount = data - 1;
      this.setState(
        {
          count: currentCount
        },
        () => {
          this.formatTime(this.state.count);
          if (currentCount === 0) {
            clearInterval(this.interval);
            this.props.endCallback(true);
          }
        }
      );
    }, 1000);
  };

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  formatTime = (seconds) => {
    // 小于等于0的话，结束倒计时
    let [hour, minute, second] = [0, 0, 0, 0];
    hour = Math.floor(seconds / (60 * 60));
    minute = Math.floor(seconds / 60) - hour * 60;
    second = Math.floor(seconds) - hour * 60 * 60 - minute * 60;

    const resultHour: string = hour < 10 ? String("0" + hour) : String(hour);
    const resultMinute: string =
      minute < 10 ? String("0" + minute) : String(minute);
    const resultSecond: string =
      second < 10 ? String("0" + second) : String(second);
    this.setState({
      resultHour,
      resultMinute,
      resultSecond
    });
  };

  render() {
    return (
      <div>
        {this.state.resultHour}
        {this.state.resultMinute}
        {this.state.resultSecond}
      </div>
    );
  }
}

Timer.defaultProps = {
  autoplay: true,
  count: 0
};
